var Composite = function(name) {
  this.name = name;
  this.type = 'Composite';
  this.children = [];
}

Composite.prototype = {
  constructor: Composite,
  addItem(item) {
    this.children.push(item);
    return this;
  },
  getItem(name) {
    var elements = [];
    // 判断对象是否为Leaf类型的,如果是直接加到elements数组中,不是继续递归调用
    var pushLeaf = function(item){
        if(item.type === 'Composite'){
            item.children.forEach(arguments.callee);
        } else if(item.type === 'Leaf'){
            elements.push(item);
        }
    };

    // 根据name 让指定name下的所有的类型为Leaf的对象去执行操作
    if(name && this.name !== name){ 
      this.children.forEach(function(item){
        // 如果传递的name是2级节点名称
        if(item.name === name && item.type === 'Composite'){
            item.children.forEach(pushLeaf);
        }
        // 如果传递的name是3级节、4级、5级...N级 
        if(item.name !== name && item.type === 'Composite'){
            item.children.forEach(arguments.callee);
        }
        // 如果传递的name是叶子节点的时候
        if(item.name === name && item.type === 'Leaf'){
            elements.push(item);
        }
      });
    } 
    // 不传递name 让整个公司所有类型为Leaf的对象去执行操作
    else {  
      this.children.forEach(pushLeaf);
    }
    
    return elements ;
  },
  hardworking:function(name){
    //得到所有的Leaf类型的对象数组
    var leafObjects = this.getItem(name);
    for(var i = 0 ; i < leafObjects.length; i ++){
      leafObjects[i].hardworking();
    }
  },
  sleeping:function(name){
    //得到所有的Leaf类型的对象数组
    var leafObjects = this.getItem(name);
    for(var i = 0 ; i < leafObjects.length; i ++){
      leafObjects[i].sleeping();
    }     
  }
};

var Leaf = function(name){
  this.name = name;
  this.type = 'Leaf';   //说明对象的类型（叶子对象）
  //创建对象的最后要验证接口
};

Leaf.prototype = {
  constructor: Leaf,
  addItem(item){
    throw new Error('this method is disabled....');
  },
  getItem(name){
    if(this.name = name){
      return this ; 
    }
    return null ;
  },
  hardworking(){
    console.log(this.name + '...努力工作!');
  },
  sleeping(){
    console.log(this.name + '...努力睡觉!');
  }       
}; 


//测试数据
var p1 = new Leaf('张1');
var p2 = new Leaf('张2');
var p3 = new Leaf('张3');
var p4 = new Leaf('张4');
var p5 = new Leaf('张5');
var p6 = new Leaf('张6');
var p7 = new Leaf('张7');
var p8 = new Leaf('张8');
var p9 = new Leaf('张9');
var p10 = new Leaf('张10');
var p11 = new Leaf('张11');
var p12 = new Leaf('张12');         
var dept1 = new Composite('北京开发部门');
dept1.addItem(p1).addItem(p2).addItem(p3);
var dept2 = new Composite('北京销售部门');
dept2.addItem(p4).addItem(p5).addItem(p6);
var dept3 = new Composite('长沙开发部门');
dept3.addItem(p7).addItem(p8).addItem(p9);
var dept4 = new Composite('长沙销售部门');
dept4.addItem(p10).addItem(p11).addItem(p12);       
var org1 = new Composite('北京分公司');
org1.addItem(dept1).addItem(dept2); 
var org2 = new Composite('长沙分公司');
org2.addItem(dept3).addItem(dept4); 

var org = new Composite('尚学堂总部');
org.addItem(org1).addItem(org2);

org.hardworking();   //尚学堂总部
